﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

public class DataOperation
{
    public void Test()
    {
        byte[] b1, b2, b3;
        string s1;
        b1 = new byte[] { 0X31, 0X32, 0X33, 0X34, 0X35, 0X35 };
        int tmp = BitConverter.ToInt32(b1, 2);   //从数组第2个字节开始的连续4个字节转为int型,高端在前
        s1 = BitConverter.ToString(b1);   //输出字符串

        b1 = new byte[] { 1, 2, 3 };
        b2 = new byte[] { 4, 5 };
        b3 = new byte[b1.Length + b2.Length];
        Buffer.BlockCopy(b1, 0, b3, 0, b1.Length);
        Buffer.BlockCopy(b2, 0, b3, b1.Length, b2.Length);

        var a1 = new int[] { 1, 2, 3 };
        var a2 = new int[] { 1, 2, 3 };
        var a3 = new int[] { 1, 2, 4 };
        var x = a1.SequenceEqual(a2); // true  //判断两个数组相等
        var y = a1.SequenceEqual(a3); // false

        int[] i = new int[] { 1, 2 };
        int[] j = new int[] { 2, 3 };
        List<int> r = new List<int>();
        r.AddRange(i);
        r.AddRange(j);
        int[] xx = i.Union(j).ToArray<int>(); //剔除重复项 
        int[] xxx = i.Concat(j).ToArray<int>(); //保留重复项
        int n = Array.BinarySearch(i, 3);       //判断数组中是否包含某个值.如果包含则返回0

    }

    public void TestString()
    {
        string str = "Hello,Kitty!"; //原始字符串
        string subString = ""; //截取后的字符串
        subString = str.Substring(0, 2);  //从第一个字符开始，截取2个字符
        subString = str.Substring(2, 3);  //从第一个‘l'开始，截取3个字符 
        subString = str.Substring(6);  //从第七个字符开始截取，到原始字符串结束 

        string s1 = "123";
        string s2 = "123";
        string[] ss1;
        char[] achar = s1.ToArray();    //字符串转字符数组
        string u = Regex.Replace("30215A", @"[^\d.\d]", "");  //只取数据部分
        achar = new char[5] { 'a', 'b', 'c', 'd', 'e' };
        byte[] bbyte = Encoding.Default.GetBytes(achar);//字符数组转字节
        char[] c = Encoding.ASCII.GetChars(bbyte);     //字节转ASCII 
        byte[] byteArray = System.Text.Encoding.ASCII.GetBytes("oiuyiuog"); //字符串转字节
        string str2 = System.Text.Encoding.Default.GetString(byteArray);     //字节转字符串

        int temp = 12345;
        str = Convert.ToString(temp, 10);  //数字转10进制字符
        str = Convert.ToString(temp, 2);   //数字转2进制字符
        str = Convert.ToString(temp, 16).ToUpper();//数字转2进制字符，并且大写

        int val = int.Parse("a456", System.Globalization.NumberStyles.HexNumber); //16进制字符串转int型

        s1 = "你的密码是什么?";
        byteArray = System.Text.Encoding.Default.GetBytes(s1); //汉字转字节
        s2 = System.Text.Encoding.Default.GetString(byteArray);       //字节转汉字
        byte[] rdata = Encoding.Default.GetBytes("中国");//将string转byte
        s2 = Encoding.Default.GetString(rdata);  //将byte转string
        rdata = Encoding.GetEncoding("UTF-8").GetBytes("中国");
        str = Encoding.Default.GetString(byteArray);
        byteArray = Encoding.ASCII.GetBytes("中国");    //字符串转字节

        Decoder d = Encoding.Default.GetDecoder();  //字节转字符
        d.GetChars(byteArray, 0, byteArray.Length, new char[1024], 0);

        s1 = "21,36,54,78,69";    //字符串截取
        ss1 = s1.Split(',');    //截取单个字符


        s1 = "sporiwpoooip[ekljkrf";
        ss1 = s1.Split('i');     //截取单个字符
        s1 = "123456789.12345789.56565656565656----";
        string[] sArray = s1.Split(new string[] { "12", "56", "-" }, StringSplitOptions.RemoveEmptyEntries);    //截取多个字符
        s1 = "aSTbvg123456rtT789V";
        s2 = s1.Substring(3, 2);  //取字符串第三个开始之后的两个字符


        s1 = "aSTbvg123456rtT789V";  //字符串大小写转换
        s2 = s1.ToUpper();           //将字符串转为大写
        s2 = s1.ToLower();           //将字符串转为小写




        ss1 = new string[] { "1", "23", "4", "678", };  //字符串拼接
        s2 = String.Join("-", s1);//字符串数组转字符串，“”内的代表连接符，如果里内是空，则无连接符，最后一个没有连接符


        s1 = "class_123456_789";        //字符串搜索
        val = s1.LastIndexOf('a');      //搜索字符返回字符所在字符串的位置
        val = s1.LastIndexOf("ufa");    //搜索字符返回字符串所在字符串的位置

        s1 = "56fsd4a6f5-fdf";
        s1.Trim('-');   //删除指定的字符
        s1 = s1.Replace("fd", ""); //删除fd,相当于把fd换成空字符
        s2 = s1.Remove(5);            //取前5个字符，后面全删除
        s2 = s1.Remove(5, 2);         //从第5个字符开始删除2个
        s2 = s1.Replace('a', '8');    //字符替换，把2换成9
        s2 = s1.Replace("aioweuro", "caoyugood");     //字符串替换
        s1 = "COM2"; s2 = "COM1";

        val = string.Compare(s2, s1, true);//两个字串符比较大小
        string result = System.Text.RegularExpressions.Regex.Replace(s1, @"[^0-9]+", "");
        string str3 = s1 + s2;   //将两个字符串合并成一个字符串

        string[] sstr1 = new string[2] { "caoyu", "good" };//将两个字符串合并成一个字符串
        string[] sstr2 = new string[] { "hello", "work", "58225" };
        string[] sstr3 = new string[sstr1.Length + sstr2.Length];
        sstr1.CopyTo(sstr3, 2);
        sstr2.CopyTo(sstr3, 1);

        s1 = "123456";
        s2 = s1.Replace('4', '-');   //字符替换，把2换成9

        List<int> listA = new List<int> { 1, 2, 3, 5, 7, 9 };
        List<int> listB = new List<int> { 13, 4, 17, 29, 2 };

        List<char> ch = new List<char>();
        ch.Add('1'); ch.Add('2'); ch.Add('3');  //按顺序增加
        ch.Insert(0, '0');                //在最前面插入0
        s1 = new string(ch.ToArray());    //转字符串


        s1 = "123456789";
        s1.Substring(5, 2);//字符串截取,从第5个截到第7个
        s1 = "Ac5d";
        s1.ToUpper();
        s1.PadLeft(10, '0');  //字符串对齐
        ss1 = new string[] { "caoyu", "caomengying", "caigong", "heyadong", "lizhiwei" };
        Array.Sort(ss1);  //字符串排序

        List<string> listC = new List<string>() { "12", "34", "56" };  //List转string
        s1 = string.Join("", listC.ToArray());

    }
    public void TestByte()
    {


    }



    //结构体
    public struct StudyType
    {
        public byte[] Data;
    }

    public static byte[] StructToBytes<T>(T obj)  //结构体转字节数据
    {
        int size = Marshal.SizeOf(typeof(T));
        IntPtr bufferPtr = Marshal.AllocHGlobal(size);
        try
        {
            Marshal.StructureToPtr(obj, bufferPtr, false);
            byte[] bytes = new byte[size];
            Marshal.Copy(bufferPtr, bytes, 0, size);
            return bytes;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in StructToBytes ! " + ex.Message);
        }
        finally
        {
            Marshal.FreeHGlobal(bufferPtr);
        }
    }


    public static object BytesToStuct(byte[] bytes, Type type)  //字节数组转结构体
    {
        //得到结构体的大小
        int size = Marshal.SizeOf(type);
        //byte数组长度小于结构体的大小
        if (size > bytes.Length)
        {
            //返回空
            return null;
        }
        //分配结构体大小的内存空间
        IntPtr structPtr = Marshal.AllocHGlobal(size);
        //将byte数组拷到分配好的内存空间
        Marshal.Copy(bytes, 0, structPtr, size);
        //将内存空间转换为目标结构体
        object obj = Marshal.PtrToStructure(structPtr, type);
        //释放内存空间
        Marshal.FreeHGlobal(structPtr);
        //返回结构体
        return obj;
    }

    public static void StructTest() //结构体转字节数据用法
    {
        StudyType s = new StudyType();
        Byte[] bytes = StructToBytes(s);
        StudyType lol = (StudyType)BytesToStuct(bytes, typeof(StudyType));//把数组转化为结构体

    }



    /////-------BYTE类型--------------------

    public static Byte[] ByteTypeConsolidation(List<Byte[]> list)  //多个LIST字节数组合并成一个字节数组
    {

        Byte[] bytes = new byte[12];
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryWriter bw = new BinaryWriter(stream);
            foreach (var item in list)
            {
                bw.Write(item);
            }
            bytes = stream.ToArray();
        }
        return bytes;
    }
    static public Byte[] DataIntercept(Byte[] datas, Int32 startPoint, Int32 endPoint)  //数据截取
    {
        return datas.Skip((Int32)startPoint).Take((Int32)endPoint).ToArray();
    }


    static public void DataClean(ref Byte[] data1, Int32 start, Int32 length, Byte data)  //数据清除
    {
        for (int i = start; i < start + length && i < data1.Length; i++)
        {
            data1[i] = data;
        }
    }
    static public string GetString(Byte[] data) //在字节数组中获取数字和英文字符
    {
        List<Byte> list = new List<Byte>();
        for (int i = 0; i < data.Length; i++)
        {
            if (data[i] < 0X20 || data[i] > 0X7F)
            {
                break;
            }
            else
            {
                list.Add(data[i]);
            }
        }
        return System.Text.Encoding.Default.GetString(list.ToArray());
    }



    static public Byte[] Aes128EncryptionAndDecryption(Byte[] data, Byte[] key, Boolean state)//加密和解密,参数1要加密或解密的数据,参数2是密码,参数3为0是加密1是解密
    {
        RijndaelManaged rm = new RijndaelManaged { Key = key, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };
        try
        {
            if (state == true)
            {
                ICryptoTransform cTransform = rm.CreateEncryptor();
                return cTransform.TransformFinalBlock(data, 0, data.Length);
            }
            else
            {
                ICryptoTransform cTransform = rm.CreateDecryptor();
                return cTransform.TransformFinalBlock(data, 0, data.Length);
            }
        }
        catch
        {
            return null;
        }
    }
    private string get_MD5(string str)
    {
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] temp;
        StringBuilder strb = new StringBuilder();
        temp = md5.ComputeHash(Encoding.Unicode.GetBytes(str));
        md5.Clear();
        for (int i = 0; i < temp.Length; i++)
        {
            strb.Append(temp[i].ToString("X").PadLeft(2, '0'));
        }
        return strb.ToString().ToLower();
    }


    /////-------STRING类型--------------------
    static public string StringSip(string s, string s1, string s2)
    {
        return s.Replace(s1, s2);
    }
    public static string StringReplaceNumber(string s)   //字符串提取数字
    {
        if (s != null && s != "")
        {
            List<Byte> bytes = new List<byte>();
            if (s[0] == '-') bytes.Add((Byte)s[0]);
            for (int i = 0; i < s.Length; i++)
            {
                if ((s[i] == '.')||(s[i] > 0X2F && s[i] < 0X3A))
                {
                    bytes.Add((Byte)s[i]);
                }
            }
            return new string(Encoding.ASCII.GetChars(bytes.ToArray()));
        }
        else { return null; }
    }
    public static string StringReplaceNumber(string s, char c)   //字符串提取数字
    {
        if (s != null)
        {
            List<Byte> bytes = new List<byte>();
            if (s[0] == '-') bytes.Add((Byte)s[0]);
            for (int i = 0; i < s.Length; i++)
            {
                if ((s[i] > 0X2F && s[i] < 0X3A) || s[i] == c)
                {
                    bytes.Add((Byte)s[i]);
                }
            }
            return new string(Encoding.ASCII.GetChars(bytes.ToArray()));
        }
        else { return s; }
    }
    public static string ByteToString(byte[] ReData, char ch)    //字节转字节字符串
    {
        return BitConverter.ToString(ReData, 0, ReData.Length).Replace('-', ch) + " ";    //字符替换，把"-"换成" "
    }
    public static string ByteToString(byte[] ReData, string s)    //字节转字节字符串
    {
        return BitConverter.ToString(ReData, 0, ReData.Length).Replace("-", s) + " ";    //字符替换，把"-"换成" "
    }
    public static byte[] StringToByte(string str, char chr) //字符"22 85 63"串字节转Byte
    {
        List<byte> Byte = new List<byte>();
        string[] sArray = str.Split(chr);
        foreach (string s in sArray)
        {
            try
            {
                Byte.Add(byte.Parse(s, System.Globalization.NumberStyles.HexNumber));
            }
            catch
            {
                break;
            }
        }
        return Byte.ToArray();
    }

    public static Byte[] StringToByte(string hexString)
    {
        List<string> Liststring = new List<string>();
        for (int i = 0; i < hexString.Length / 2 + hexString.Length % 2; i++)
        {
            if (2 * i + 2 <= hexString.Length)
            {
                Liststring.Add(hexString.Substring(2 * i, 2));
            }
            else
            {
                if (hexString.Length % 2 == 1)
                {
                    Liststring.Add("0" + hexString.Substring(hexString.Length - 1));
                    break;
                }
            }
        }
        return DataOperation.StringToByte(string.Join(" ", Liststring), ' ');
    }

    public string[] StringOrder(string[] str)  //字符串排序
    {
        for (int i = 0; i < str.Length - 1; i++)
        {
            for (int j = 0; j < str.Length - 1 - i; j++)
            {
                //if (str[j].CompareTo(str[j + 1]) > 0) //字符串大小排序
                if (Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(str[j], @"[^0-9]+", "")) > Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(str[j + 1], @"[^0-9]+", "")))
                {
                    string s = str[j];
                    str[j] = str[j + 1];
                    str[j + 1] = s;
                }
            }
        }
        return str;
    }

    static public bool CompareArr(string[] arr1, string[] arr2)  //比较两个字符串内容是否互相包含
    {
        var q = from a in arr1 join b in arr2 on a equals b select a;
        bool flag = arr1.Length == arr2.Length && q.Count() == arr1.Length;
        return flag;        //内容相同返回true,反之返回false。
    }
    static public bool CompareArr(string arr1, string arr2)  //比较两个字符串内容是否互相包含
    {
        var q = from a in arr1 join b in arr2 on a equals b select a;
        bool flag = arr1.Length == arr2.Length && q.Count() == arr1.Length;
        return flag;        //内容相同返回true,反之返回false。
    }
    static public bool CompareArr(byte[] arr1, byte[] arr2)  //比较两个字符串内容是否互相包含
    {
        var q = from a in arr1 join b in arr2 on a equals b select a;
        bool flag = arr1.Length == arr2.Length && q.Count() == arr1.Length;
        return flag;        //内容相同返回true,反之返回false。
    }
}
